package com.example.graduatetest.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.example.graduatetest.R;
import com.example.graduatetest.activitys.CardDetailActivity;
import com.example.graduatetest.activitys.ClassDetailActivity;
import com.example.graduatetest.bean.Card;
import com.example.graduatetest.bean.Classes;
import com.example.graduatetest.callback.OneClassCallBack;
import com.example.graduatetest.callback.StringCallBack;
import com.example.graduatetest.model.CardModel;
import com.example.graduatetest.model.ClassModel;

import java.util.List;

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
    private List<Card> cardList;
    private SparseArray<CountDownTimer> countDownMap = new SparseArray<>();
    private Handler handler = new Handler();
    private Activity activity;

    static class ViewHolder extends  RecyclerView.ViewHolder{
        TextView current_time;
        TextView card_code;
        TextView clock_text;
        TextView address_text;
        TextView all_number;
        TextView in_number;
        TextView out_number;
        TextView delay_number;
        TextView ask_number;
        TextView class_id;
        TextView class_name;
        ConstraintLayout constraintLayout;
        CountDownTimer countDownTimer;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            current_time = (TextView)itemView.findViewById(R.id.tv_current_time);
            card_code = (TextView)itemView.findViewById(R.id.tv_card_code);
            clock_text = (TextView)itemView.findViewById(R.id.tv_clock_text);
            address_text = (TextView)itemView.findViewById(R.id.tv_address);
            all_number = (TextView)itemView.findViewById(R.id.tv_class_all_number);
            in_number = (TextView)itemView.findViewById(R.id.tv_class_in_number);
            out_number = (TextView)itemView.findViewById(R.id.tv_class_out_number);
            ask_number = (TextView)itemView.findViewById(R.id.tv_class_ask_number);
            delay_number = (TextView)itemView.findViewById(R.id.tv_class_delay_number);
            class_id = (TextView)itemView.findViewById(R.id.tv_class_number);
            class_name = (TextView)itemView.findViewById(R.id.tv_class_name);
            constraintLayout = (ConstraintLayout)itemView.findViewById(R.id.card_item);
        }
    }
    public CardAdapter(List<Card> cardList,Activity activity){
        this.cardList = cardList;
        this.activity = activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_code_item, parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public int getItemCount() {
        return cardList.size();
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        final Card card = cardList.get(position);
        holder.ask_number.setText(String.valueOf(card.getAsk_number()));
        holder.out_number.setText(String.valueOf(card.getOut_number()));
        holder.clock_text.setText(String.valueOf(card.getStay_s())+" s");
        holder.current_time.setText(card.getTime());
        holder.all_number.setText(String.valueOf(card.getAll_number()));
        holder.in_number.setText(String.valueOf(card.getIn_number()));
        holder.delay_number.setText(String.valueOf(card.getDelay_number()));
        holder.address_text.setText(card.getAddress());
        holder.card_code.setText(card.getCode());
        holder.class_id.setText(card.getClass_number());

        CardModel.getOneClass(card.getClass_number(), new OneClassCallBack() {
            @Override
            public void onSuccess(final Classes classes) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        holder.class_name.setText(classes.getName());
                    }
                });
                Log.e("haha", "获取name成功");
            }

            @Override
            public void onFailed() {
               Log.e("haha", "获取name失败");
            }
        });


        long betweenDate =  card.getStay_s();
        final String card_id = card.getId();


        if (holder.countDownTimer != null) {
            holder.countDownTimer.cancel();
        }

        if (betweenDate > 0 && card.getStatus().equals("正在考勤")) {
            holder.countDownTimer = new CountDownTimer(betweenDate*1000, 1000) {
                public void onTick(long millisUntilFinished) {
                    String value = String.valueOf((int) (millisUntilFinished / 1000));
                    holder.clock_text.setText(value+" s");
                }
                public void onFinish() {
                    holder.clock_text.setText("考勤结束");
                    changeStatus(card_id);
//                    时间结束后进行相应逻辑处理
                }
            }.start();
            countDownMap.put(holder.clock_text.hashCode(), holder.countDownTimer);
        }else{
//            时间结束 进行相应逻辑处理
            holder.clock_text.setText("考勤结束");

        }

        //设置item的点击事件
        holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Card cardSend = cardList.get(position);
                Intent intent = new Intent(activity.getApplication(), CardDetailActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("card", cardSend);
                activity.getApplication().startActivity(intent);
            }
        });
    }

    //倒计时结束后修改服务器card的状态
    private void changeStatus(String id){
        CardModel.setStatusFunction(id, new StringCallBack() {
            @Override
            public void onSuccess(String result) {
                if(result.equals("success")){
                    Log.e("haha", "状态更新成功");
                }else{
                    Log.e("haha", "状态更新失败");
                }
            }

            @Override
            public void onFailed() {
                Log.e("haha", "状态更新失败");
            }
        });
    }

    @Override
    public void onViewRecycled(@NonNull ViewHolder holder) {
        super.onViewRecycled(holder);
        //cancelAllTimers();
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownMap == null) {
            return;
        }
        for (int i = 0,length = countDownMap.size(); i < length; i++) {
            CountDownTimer cdt = countDownMap.get(countDownMap.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }
}
